#include <pthread.h>
#include <iostream>
#include <string>
#include <functional>

namespace my_thread
{
    using func_t = std::function<void(const std::string& name)>;

    class mythread
    {
    public:
        mythread(func_t func, const std::string name = "thread")
        : _func(func),  _name(name)
        {}
        
        void mission()
        {
            _func(_name);
        }

        static void* run_mission(void* arg) //方法必须是static的，否则有this指针，不能作为pthread_create的方法参数
        {
            mythread *self = static_cast<mythread*>(arg);
            self->mission();
            return nullptr;
        }

        bool Start()
        {
            if (_stop)
            {
                int ret = pthread_create(&_tid, nullptr, run_mission, this);    //将参数设置为this指针，方便后续调用任务
                if (ret == 0)
                {
                    _stop = false;
                    //std::cout << "thread create success, " << _name << std::endl;

                    return true;
                }
                else
                    return false;
            }
            return true;
        }

        void Join()
        {
            if (!_stop)
                pthread_join(_tid, nullptr);
        }

        void Detach()
        {
            if (!_stop)
                pthread_detach(_tid);
        }

        void Stop()
        {
            _stop = true;
        }

        pthread_t Tid()
        {
            return _tid;
        }

    private:
        std::string _name;
        pthread_t _tid;
        func_t _func;
        bool _stop = true;
    };
}